<template>
  <div class="recharge-container">
    <el-card class="recharge-card">
      <template #header>
        <div class="card-header">
          <h2>账户充值</h2>
          <el-button type="default" icon="el-icon-arrow-left" size="small" @click="backToPersonalCenter">返回个人中心</el-button>
        </div>
      </template>
      
      <div class="recharge-content">
        <el-form :model="rechargeForm" label-width="80px" ref="rechargeFormRef" :rules="rules">
          <el-form-item label="充值金额" prop="amount">
            <el-input-number v-model="rechargeForm.amount" 
            :min="0.00"
            :precision="2" 
            :step="10" 
            :controls="false" 
            :disabled="true"
            style="width: 200px;" />
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="支付方式" prop="payMethod">
            <el-radio-group v-model="rechargeForm.payMethod">
              <el-radio label="alipay">
                <img src="../assets/alipay-logo.svg" alt="支付宝" class="payment-logo" />
                支付宝
              </el-radio>
              <el-radio label="wechat">
                <img src="../assets/wechat-logo.svg" alt="微信支付" class="payment-logo" />
                微信支付
              </el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="备注" prop="description">
            <el-input v-model="rechargeForm.description" placeholder="选填" style="width: 300px;" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitRecharge" :loading="loading">立即充值</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 微信支付二维码弹窗 -->
        <el-dialog v-model="wechatPayVisible" title="微信支付" width="400px" center>
          <div class="qrcode-container">
            <div id="wechat-qrcode" ref="wechatQrcode"></div>
            <p class="qrcode-tip">请使用微信扫一扫完成支付</p>
            <p class="qrcode-amount">￥{{ rechargeForm.amount }}</p>
          </div>
          <div class="qrcode-footer">
            <el-button @click="checkPaymentStatus" :loading="checkingStatus">检查支付状态</el-button>
            <el-button @click="wechatPayVisible = false">取消</el-button>
          </div>
        </el-dialog>
        
        <!-- 支付宝表单容器，用于提交支付宝表单 -->
        <div ref="alipayFormContainer" style="display: none;"></div>
      </div>
    </el-card>
    
    <!-- 交易记录 -->
    <el-card class="transaction-card">
      <template #header>
        <div class="card-header">
          <h2>交易记录</h2>
          <el-button type="primary" size="small" @click="loadTransactions">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="transactions" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="createdAt" label="时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="rechargeType" label="类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.rechargeType)">
              {{ getTypeName(scope.row.rechargeType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="scope">
            <span :class="{ 'amount-positive': scope.row.amount > 0, 'amount-negative': scope.row.amount < 0 }">
              {{ scope.row.amount > 0 ? '+' : '' }}{{ scope.row.amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="scope">
            {{ getPayMethodName(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import QRCode from 'qrcodejs2-fix';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

// 确保引入了正确的API
import { getTransactions } from '@/api/account';
import { createPaymentOrder, queryPaymentStatus } from '@/api/payment';
import { getUserInfo } from '@/api/user'; // 从user.js导入getUserInfo，而不是auth.js

export default {
  name: 'Recharge',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const rechargeFormRef = ref(null);
    const alipayFormContainer = ref(null);
    const wechatQrcode = ref(null);
    const userInfo = ref(null); // 用于存储用户信息
    
    // 充值表单
    const rechargeForm = reactive({
      amount: 100,
      payMethod: 'alipay',
      description: '账户充值'
    });
    
    // 表单验证规则
    const rules = {
      amount: [
        { required: true, message: '请输入充值金额', trigger: 'blur' },
        { type: 'number', min: 0.00, message: '充值金额必须大于0.00', trigger: 'blur' }
      ],
      payMethod: [
        { required: true, message: '请选择支付方式', trigger: 'change' }
      ]
    };
    
    // 状态变量
    const loading = ref(false);
    const wechatPayVisible = ref(false);
    const checkingStatus = ref(false);
    const currentOrderNo = ref('');
    const tableLoading = ref(false);
    const transactions = ref([]);
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfo();
        
        if (res && res.code === 200 && res.data) {
          userInfo.value = res.data;
          
          // 将用户信息保存到localStorage，以便其他地方使用
          localStorage.setItem('userInfo', JSON.stringify(res.data));
          
          return true;
        } else {
          ElMessage.error('获取用户信息失败: ' + (res?.msg || '未知错误'));
          return false;
        }
      } catch (error) {
        ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'));
        return false;
      }
    };
    
    // 返回个人中心
    const backToPersonalCenter = () => {
      router.push('/personal-center');
    };
    
    // 加载交易记录
    const loadTransactions = async () => {
      tableLoading.value = true;
      try {
        // 使用API函数而不是直接调用axios
        const res = await getTransactions({ type: '' });
        
        if (res && res.code === 200 && res.data) {
          transactions.value = res.data;
        } else {
          ElMessage.warning('获取交易记录失败');
        }
      } catch (error) {
        ElMessage.error('获取交易记录失败');
      } finally {
        tableLoading.value = false;
      }
    };
    
    // 提交充值
    const submitRecharge = async () => {
      if (!rechargeFormRef.value) return;
      
      await rechargeFormRef.value.validate(async (valid) => {
        if (!valid) return;
        
        loading.value = true;
        try {
          // 获取用户信息的多种方式
          let phone = '';
          
          // 方法1：从组件中的userInfo获取
          if (userInfo.value && userInfo.value.phone) {
            phone = userInfo.value.phone;
          } 
          // 方法2：从localStorage获取
          else {
            const userInfoStr = localStorage.getItem('userInfo');
            if (userInfoStr) {
              try {
                const parsedUserInfo = JSON.parse(userInfoStr);
                phone = parsedUserInfo.phone;
              } catch (e) {

              }
            }
          }
          
          // 方法3：如果前两种方法都失败，尝试重新获取用户信息
          if (!phone) {
            const success = await fetchUserInfo();
            if (success && userInfo.value && userInfo.value.phone) {
              phone = userInfo.value.phone;
            }
          }
          
          if (!phone) {
            ElMessage.error('获取用户信息失败，请重新登录');
            setTimeout(() => {
              router.push('/login');
            }, 1500);
            loading.value = false;
            return;
          }
          
          // 构建请求参数
          const params = {
            amount: rechargeForm.amount,
            paymentType: rechargeForm.payMethod === 'wechat' ? 1 : 2, // 1-微信支付，2-支付宝支付
            packageType: route.query.productType || 'CUSTOM', // 从URL获取产品类型，默认为自定义充值
            description: rechargeForm.description || '账户充值',
            phone: phone // 添加手机号参数
          };
          
          // 如果是套餐购买，添加套餐ID
          if (route.query.packageId) {
            params.packageId = route.query.packageId;
          }
          
          // 处理邮件套餐的额外参数
          if (route.query.productType === 'EMAIL') {
            // 使用packageId作为套餐ID
            params.packageId = route.query.packageId;
            
            // 使用packageId作为packagePoints，这将用于查找邮件套餐
            params.packagePoints = parseInt(route.query.packageId);
            
            // 使用packageLevel作为套餐等级
            params.packageLevel = route.query.packageLevel || "1";
            
            // 使用duration作为套餐时长
            params.packageDuration = route.query.duration || "0";
            
          } 
          // 处理VIP套餐的额外参数
          else if (route.query.productType === 'VIP') {
            // 使用packageId作为packagePoints
            params.packagePoints = parseInt(route.query.packageId);
            
            // 使用duration作为packageDuration
            params.packageDuration = route.query.duration || "1";
          }
          // 调用创建支付订单接口
          const res = await createPaymentOrder(params);
          
          if (res && res.code === 200 && res.data) {
            // 保存订单号
            currentOrderNo.value = res.data.orderNo;
            
            if (rechargeForm.payMethod === 'alipay') {
              // 支付宝支付
              if (alipayFormContainer.value && res.data.form) {
                alipayFormContainer.value.innerHTML = res.data.form;
                
                // 自动提交表单
                const form = alipayFormContainer.value.querySelector('form');
                if (form) {
                  form.submit();
                } else {
                  ElMessage.error('生成支付表单失败');
                }
              } else {
                ElMessage.error('支付表单生成失败');
              }
            } else if (rechargeForm.payMethod === 'wechat') {
              // 微信支付
              wechatPayVisible.value = true;
              
              // 等待DOM更新后生成二维码
              nextTick(() => {
                if (wechatQrcode.value && res.data.codeUrl) {
                  wechatQrcode.value.innerHTML = '';
                  try {
                    new QRCode(wechatQrcode.value, {
                      text: res.data.codeUrl,
                      width: 200,
                      height: 200,
                      colorDark: '#000000',
                      colorLight: '#ffffff',
                      correctLevel: QRCode.CorrectLevel.H
                    });
                  } catch (e) {
                    ElMessage.error('生成支付二维码失败');
                  }
                } else {
                  ElMessage.error('生成支付二维码失败');
                }
              });
            }
          } else {
            ElMessage.error(res?.msg || '创建支付订单失败');
          }
        } catch (error) {
          ElMessage.error('充值请求失败: ' + (error.message || '未知错误'));
        } finally {
          loading.value = false;
        }
      });
    };
    
    // 检查支付状态
    const checkPaymentStatus = async () => {
      if (!currentOrderNo.value) {
        ElMessage.warning('订单号不存在');
        return;
      }
      
      checkingStatus.value = true;
      try {
        // 使用API函数而不是直接调用axios
        const res = await queryPaymentStatus(currentOrderNo.value);
        
        if (res && res.code === 200 && res.data) {
          if (res.data.status === 1) { // 已支付
            ElMessage.success('支付成功');
            wechatPayVisible.value = false;
            await router.push('/personal-center')
            await loadTransactions();
          } else if (res.data.status === 0) { // 未支付
            ElMessage.info('支付未完成，请扫码支付');
          } else if (res.data.status === 2) { // 已取消
            ElMessage.warning('订单已取消');
            wechatPayVisible.value = false;
          }
        } else {
          ElMessage.warning('查询支付状态失败');
        }
      } catch (error) {
        ElMessage.error('查询支付状态失败');
      } finally {
        checkingStatus.value = false;
      }
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    };
    
    // 获取类型标签样式
    const getTypeTag = (type) => {
      switch (type) {
        case 'VIP': return 'success';
        case 'EMAIL': return 'warning';
        case 'CUSTOM': return 'primary';
        default: return 'info';
      }
    };
    
    // 获取类型名称
    const getTypeName = (type) => {
      switch (type) {
        case 'VIP': return 'VIP充值';
        case 'EMAIL': return '邮件套餐';
        case 'CUSTOM': return '余额充值';
        default: return '其他';
      }
    };
    
    // 获取支付方式名称
    const getPayMethodName = (method) => {
      switch (method) {
        case 'ALIPAY': return '支付宝';
        case 'WECHAT': return '微信支付';
        case 'SYSTEM': return '系统';
        default: return method || '未知';
      }
    };
    
    // 组件挂载时
    onMounted(async () => {
      // 检查是否已登录
      const token = localStorage.getItem('token');
      if (!token) {
        ElMessage.error('您尚未登录，请先登录');
        setTimeout(() => {
          router.push('/login');
        }, 1500);
        return;
      }
      
      // 获取用户信息
      await fetchUserInfo();
      
      // 加载交易记录
      loadTransactions();
      
      // 检查URL参数，处理支付宝支付成功后的跳转
      if (route.query.status === 'success') {
        ElMessage.success('支付成功');
        // 刷新交易记录
        setTimeout(() => {
          loadTransactions();
        }, 1000);
      }
      
      // 处理从会员中心传来的升级或购买套餐参数
      if (route.query.packageId && route.query.amount && route.query.productType) {
        // 设置充值金额
        rechargeForm.amount = Number(route.query.amount);
        
        // 设置套餐描述
        if (route.query.productType === 'VIP') {
          rechargeForm.description = `购买${route.query.packageName || '会员套餐'} ${route.query.duration || ''}个月`;
        } else if (route.query.productType === 'EMAIL') {
          rechargeForm.description = `购买${route.query.packageName || '邮件套餐'} ${route.query.emailCount || ''}封`;
        }
        
        // 提示用户
        ElMessage.info(`正在为您准备${route.query.productType === 'VIP' ? '会员升级' : '邮件套餐购买'}，请确认支付方式后点击"立即充值"`);
      }
    });
    
    return {
      rechargeForm,
      rechargeFormRef,
      alipayFormContainer,
      wechatQrcode,
      rules,
      loading,
      wechatPayVisible,
      checkingStatus,
      tableLoading,
      transactions,
      submitRecharge,
      checkPaymentStatus,
      loadTransactions,
      formatDate,
      getTypeTag,
      getTypeName,
      getPayMethodName,
      backToPersonalCenter
    };
  }
};
</script>

<style scoped>
.recharge-container {
  padding: 20px;
}

.recharge-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recharge-content {
  padding: 10px;
}

.payment-logo {
  height: 24px;
  margin-right: 5px;
  vertical-align: middle;
}

.unit {
  margin-left: 10px;
  color: #666;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.qrcode-tip {
  margin-top: 15px;
  color: #666;
}

.qrcode-amount {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
  margin-top: 10px;
}

.qrcode-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount-positive {
  color: #67c23a;
}

.amount-negative {
  color: #f56c6c;
}
</style> 